﻿using System;

namespace Eventless
{
    public sealed class Writeable<T> : IWriteable<T>, IEquate<T>
    {
        private T _value;

        public Writeable(T value = default(T))
        {
            _value = value;
            EqualityComparer = DefaultEqualityComparer;
        }

        public T Value
        {
            get
            {
                Computations.Reading(this);
                return _value;
            }

            set
            {
                if (EqualityComparer(_value, value))
                    return;

                _value = value;
                var evt = Changed;
                if (evt != null)
                    evt();
            }
        }

        public event Action Changed;

        public Func<T, T, bool> EqualityComparer { get; set; }

        public static bool DefaultEqualityComparer(T a, T b)
        {
            if (ReferenceEquals(a, b))
                return true;
            return !ReferenceEquals(a, null) && a.Equals(b);
        }
    }

    public static class Writeable
    {
        public static Writeable<T> From<T>(T initVal)
        {
            return new Writeable<T>(initVal);
        }
    }
}